<template>
  <div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Button
        v-hasC="{
          name: 'base-project-create',
          flag: 'v1/base/project/create',
        }"
        type="primary"
        @click="handleAllocation(-1)"
        >新增</Button
      >
      <Table
        highlight-row
        :columns="columns"
        :data="data"
        class="ivu-mt-16"
        :loading="loading"
      >
        <template slot="num" slot-scope="{ row }">
          <a @click="handleSetups(row)">{{ row.num }}</a>
        </template>
        <template slot-scope="{ row }" slot="status">
          <Badge v-if="row.status === '1'" status="success" text="正常" />
          <Badge v-if="row.status === '0'" status="error" text="停用" />
        </template>
        <template slot-scope="{ row }" slot="operation">
          <a
            v-hasC="{
              name: 'base-project-update',
              flag: 'v1/base/project/update',
            }"
            @click="handleAllocation(row)"
            >编辑</a
          >
          <Divider
            v-hasCC="[
              {
                name: 'base-project-update',
                flag: 'v1/base/project/update',
              },
              {
                name: 'base-project-update-config',
                flag: 'v1/base/project/update-project-config',
              },
            ]"
            type="vertical"
          />
          <a
            v-hasC="{
              name: 'base-project-update-config',
              flag: 'v1/base/project/update-project-config',
            }"
            @click="handleSetup(row)"
            >配置</a
          >
        </template>
      </Table>
      <div class="ivu-mt" style="display: flex; justify-content: center;">
        <Page
          show-total
          show-elevator
          show-sizer
          :total="total"
          :current.sync="params.page"
          :page-size="params.pageSize"
          :page-size-opts="pageOpts"
          @on-change="formSize"
          @on-page-size-change="formChangePage"
        />
      </div>
    </Card>
    <Modal
      v-model="modal"
      :title="edit ? '新增' : '编辑'"
      @on-cancel="handleDrawerCancel('formItem')"
    >
      <Form
        :model="formItem"
        :label-width="100"
        ref="formItem"
        :rules="createRules"
      >
        <FormItem label="名称" prop="name">
          <Input v-model.trim="formItem.name" placeholder="请输入名称" />
        </FormItem>
        <FormItem label="科室" prop="section_id">
          <Select v-model="formItem.section_id">
            <Option
              :value="item.id"
              v-for="item in section_list"
              :key="item.id"
              >{{ item.section_name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="排序">
          <Input
            v-width="100"
            v-model.trim="formItem.sort"
            placeholder=""
            type="number"
            @on-blur="sortNum"
          />
        </FormItem>
        <FormItem label="状态">
          <i-switch v-model="formItem.status">
            <span slot="open">On</span>
            <span slot="close">Off</span>
          </i-switch>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="handleDrawerCancel('formItem')">取消</Button>
        <Button
          type="primary"
          :loading="remarksloading"
          @click="handleSubmit('formItem', 1)"
          >确定</Button
        >
      </div>
    </Modal>
    <Modal
      v-model="setupModal"
      title="配置"
      @on-cancel="handleDrawerCancel('formItems')"
    >
      <Form
        :model="paramsconfig"
        ref="formItems"
        :rules="createRules"
        label-position="top"
      >
        <FormItem label="关联白友项目" prop="relation_baiyou_pname">
          <Select v-model="paramsconfig.relation_baiyou_pname">
            <Option
              :value="item.name"
              v-for="item in projectlist"
              :key="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="选择默认城市">
          <!-- <Select v-model="paramsconfig.default_city">
                        <Option
                            :value="item.name"
                            v-for="item in projectlist"
                            :key="item.id"
                            >{{ item.name }}</Option
                        >
                    </Select> -->
          <Select
            v-model="paramsconfig.default_city"
            v-if="cityshow"
            placeholder="请输入城市拼音简写"
            filterable
            remote
            clearable
            :remote-method="remoteMethod"
            :loading="loadingcity"
          >
            <Option
              v-for="item in optionscity"
              :key="item.value"
              :value="item.key"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>

        <FormItem label="市场部门数据跟进">
          <Select v-model="paramsconfig.marketing_follow_did">
            <Option
              :value="item.value"
              v-for="item in dataprojectlist"
              :key="item.id"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="handleDrawerCancel('formItems')">取消</Button>
        <Button
          type="primary"
          :loading="remarksloading"
          @click="handleSubmit('formItems', 2)"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  baseprojectindex,
  baseprojectupdateprojectconfig,
  baseprojectcreate,
  baseprojectupdate,
  patientindexsearchcity,
  checkDisease,
} from "@api/hqapi";
export default {
  name: "diagnosis",
  data() {
    return {
      cityshow: true,
      modal: false,
      loadingcity: false,
      optionscity: [],
      dataprojectlist: [],
      setupModal: false,
      formItem: {
        id: undefined,
        name: "",
        status: "",
        section_id: "",
        sort: "",
      },
      projectlist: [],
      diseasesList: [],
      columns: [
        { title: "项目ID", key: "id", width: 100 },
        { title: "名称", key: "name", minWidth: 108 },
        { title: "在职人数", slot: "num", width: 118 },
        {
          title: "关联白友项目",
          key: "relation_baiyou_pname",
          minWidth: 150,
        },
        { title: "科室", key: "section_name", minWidth: 150 },
        { title: "排序", key: "sort", minWidth: 150 },
        {
          title: "默认城市",
          key: "city_name",
          minWidth: 150,
          ellipsis: true,
          tooltip: true,
        },
        { title: "状态", slot: "status", minWidth: 90 },
        { title: "操作", slot: "operation", fixed: "right", width: 118 },
      ],
      data: [],
      loading: false,
      edit: true,
      remarksloading: false,
      createRules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        section_id: [
          {
            required: true,
            message: "请选择科室",
            trigger: "change",
          },
        ],
        relation_baiyou_pname: [
          {
            required: false,
            message: "请输入名称",
            trigger: "change",
          },
        ],
      }, // 模态框验证规则
      section_list: [],
      params: { page: 1, pageSize: 10 },
      paramsconfig: {
        id: undefined,
        relation_baiyou_pname: "",
        default_city: "",
        marketing_follow_did: "",
      },
      total: 0,
      pageOpts: [10, 15, 20, 30, 50], // 分页每页数量
    };
  },
  /* 创建完成能访问this实例 */
  mounted() {
    this.initial();
  },
  /* 函数方法集合 */
  methods: {
    /* @函数功能: 初始化 */
    initial() {
      this.askData();
      // this._diseasesProject()
    },
    /* @函数功能: 请求数据 */
    askData() {
      this.loading = true;
      baseprojectindex(this.params).then((res) => {
        this.projectlist = res.baiyou_project;
        this.section_list = res.section_list;
        this.diseasesList = res.disease_list; //获取病种数据
        this.data = res.list.list;
        this.total = res.list.total;
        let list = [];
        for (let item of res.department_list) {
          list.push({ label: item.label, value: item.value });
          list.push(...item.children);
        }
        this.dataprojectlist = list;
        this.loading = false;
      });
    },
    /* @函数功能: 分页 */
    formSize(e) {
      this.params.page = e;
      this.askData();
    },
    /* @函数功能: 每页数量 */
    formChangePage(e) {
      this.params.pageSize = e;
      this.askData();
    },
    //获取病种数据
    // _diseasesProject(){
    //     diseasesProject().then(res=>{
    //         this.diseasesList=res.disease_list
    //     })
    // },
    sortNum() {
      if (this.formItem.sort < 0) {
        this.formItem.sort = 0;
      }
    },
    // 城市搜索
    remoteMethod(query) {
      if (query !== "") {
        if (parseFloat(query).toString() !== "NaN")
          query = query.slice(6, query.length);
        this.loadingcity = true;
        return new Promise((resolve) => {
          setTimeout(() => {
            patientindexsearchcity({
              keywords: query,
            }).then((res) => {
              if (res.list && res.list.length > 0) {
                const list = res.list.map((item) => {
                  return {
                    key: `${item.value} ${query}`,
                    value: item.value,
                    label: item.label,
                  };
                });
                this.optionscity = list;
              }
              resolve(res.data);
            });
            this.loadingcity = false;
          }, 200);
        });
      } else {
        this.optionscity = [];
      }
    },
    /* 打开模态框 */
    handleAllocation(row) {
      if (row === -1) {
        this.edit = true;
        this.formItem = {
          id: undefined,
          name: "",
          status: true,
          section_id: "",
          sort: "",
        };
      } else {
        this.edit = false;
        this.formItem = {
          id: row.id,
          name: row.name,
          status: +row.status === 1,
          section_id: row.section_id,
          sort: row.sort,
        };
      }
      this.modal = true;
    },
    /* 取消 */
    handleDrawerCancel(name) {
      this.$refs[name].resetFields();
      this.modal = false;
      this.setupModal = false;
      this.formItem = {
        id: undefined,
        name: "",
        status: true,
        section_id: "",
        sort: "",
      };
      this.paramsconfig = {
        id: undefined,
        relation_baiyou_pname: "",
      };
    },
    /* 提交 */
    handleSubmit(name, num) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.remarksloading = true;
          if (num === 1) {
            let config = {
              id: this.formItem.id,
              name: this.formItem.name,
              status: this.formItem.status ? 1 : 0,
              section_id: this.formItem.section_id,
              sort: Number(this.formItem.sort),
            };
            if (!this.edit) {
              baseprojectupdate(config)
                .then(() => {
                  this.$Message.success("编辑成功");
                  this.askData();
                  this.modal = false;
                  this.remarksloading = false;
                })
                .catch(() => {
                  this.remarksloading = false;
                });
            } else {
              baseprojectcreate(config)
                .then(() => {
                  this.$Message.success("新增成功");
                  this.askData();
                  this.modal = false;
                  this.remarksloading = false;
                })
                .catch(() => {
                  this.remarksloading = false;
                });
            }
          } else {
            let config = JSON.parse(JSON.stringify(this.paramsconfig));
            baseprojectupdateprojectconfig(config)
              .then(() => {
                this.$Message.success("关联成功");
                this.askData();
                this.setupModal = false;
                this.remarksloading = false;
              })
              .catch(() => {
                this.remarksloading = false;
              });
          }
        }
      });
    },
    /* 打开模态框 */
    handleSetup(row) {
      this.cityshow = false;
      this.paramsconfig.id = row.id;
      this.paramsconfig.relation_baiyou_pname = row.relation_baiyou_pname;
      this.paramsconfig.default_city =
        +row.default_city !== 0 ? row.default_city : "";
      this.paramsconfig.marketing_follow_did = row.marketing_follow_did;
      if (this.paramsconfig.default_city) {
        this.optionscity = [
          {
            key: this.paramsconfig.default_city,
            value: this.paramsconfig.default_city,
            label: row.city_name,
          },
        ];
      }
      setTimeout(() => {
        this.cityshow = true;
      }, 1);
      this.setupModal = true;
    },
    handleSetups(row) {
      this.$router.push({
        path: "/setting/clique/power/person",
        query: { id: row.id },
      });
    },
  },
};
</script>

<style scoped></style>
